<template>
  <div>
    <el-form label-width="100px">
      <el-form-item label="SPU名称"> {{spu.spuName}} </el-form-item>
      <el-form-item label="SKU名称">
        <el-input placeholder="SKU名称" v-model="skuForm.skuName"></el-input>
      </el-form-item>
      <el-form-item label="价格">
        <el-input 
        placeholder="价格" 
        type="number" 
        v-model="skuForm.price"></el-input>
      </el-form-item>
      <el-form-item label="重量">
        <el-input 
        placeholder="重量" 
        type="number" 
        v-model="skuForm.weight"></el-input>
      </el-form-item>
      <el-form-item label="规格描述">
        <el-input
        placeholder="规格描述" 
        type="textarea" 
        rows="4" 
        v-model="skuForm.skuDesc"></el-input>
      </el-form-item>

      <el-form-item label="平台属性">
        <el-form :inline="true" label-width="100px">
          <el-form-item 
          :label="attr.attrName" 
          v-for="(attr, index) in attrList" 
          :key="attr.id">
            <el-select v-model="attr.attrIdValueId">
              <el-option 
              :label="attrValue.valueName" 
              :value="`${attr.id}:${attrValue.id}`"
                v-for="(attrValue, index) in attr.attrValueList" 
                :key="attrValue.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>

      <el-form-item label="销售属性">
        <el-form :inline="true" label-width="100px">
          <el-form-item 
          :label="saleAttr.saleAttrName" 
          v-for="(saleAttr, index) in spuSaleAttrList" 
          :key="saleAttr.id">
            <el-select v-model="saleAttr.saleAttrIdValueId">
              <el-option 
              :label="saleAttrValue.saleAttrValueName" 
              :value="`${saleAttr.id}:${saleAttrValue.id}`"
                v-for="(saleAttrValue, index) in saleAttr.spuSaleAttrValueList" :key="saleAttrValue.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>

      <el-form-item label="图片列表">
        <el-table border stripe :data="spuImageList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column label="图片">
            <template v-slot="{ row, $index }">
              <el-image :src="row.imgUrl" style="width: 100px; height: 60px"></el-image>
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="imgName"></el-table-column>
          <el-table-column label="操作">
            <template v-slot="{ row, $index }">
              <el-button type="primary" size="small" v-if="row.isDefault==='0'"
                @click="setDefaultImg(row,spuImageList)">设为默认</el-button>
              <el-tag type="danger" size="small" v-else>默认</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="save">保存</el-button>
        <el-button @click="emits('changeState', 1)">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { storeToRefs } from "pinia";
import { ElMessage } from "element-plus";
export default defineComponent({
  name: "SkuForm", //组件名称
});
</script>
<script lang="ts" setup>
import type { SpuData, SpuSaleAttrData } from "@/api/spu";
import { ref, onMounted, reactive } from "vue";
import attrApi, { type AttrData } from "@/api/attr";
import skuApi, {
  type SkuData,
  type SkuImageData,
  type SpuImageData,
  type SkuAttrValueData,
  type SkuSaleAttrValueData,
} from "@/api/sku";
import { useCategoryStore } from "@/stores/category";
const categoryStore = useCategoryStore();
const props = defineProps<{
  spu: SpuData;
}>();
const emits = defineEmits(["changeState"]);

const { category1Id, category2Id, category3Id } = storeToRefs(categoryStore);

const attrList = ref<AttrData[]>([]);
const spuSaleAttrList = ref<SpuSaleAttrData[]>([]);
const spuImageList = ref<SpuImageData[]>([]);

const getAddSkuFormInitData = async () => {
  // 根据选中的123级id获取平台属性列表
  // http://localhost:3000/app-dev/admin/product/attrInfoList/2/13/61
  const promise1 = attrApi.getList(
    category1Id.value as number,
    category2Id.value as number,
    category3Id.value as number
  );
  // 根据spu的id获取spu的销售属性列表
  // http://localhost:3000/app-dev/admin/product/spuSaleAttrList/4
  const promise2 = skuApi.getSpuSaleAttrList(props.spu.id as number);
  // 根据spu的id获取spu的图片列表
  // http://localhost:3000/app-dev/admin/product/spuImageList/4
  const promsie3 = skuApi.getSpuImageList(props.spu.id as number);
  try {
    const result = await Promise.all([promise1, promise2, promsie3]);
    attrList.value = result[0];
    spuSaleAttrList.value = result[1];
    spuImageList.value = result[2];
    spuImageList.value.forEach((item) => {
      item.isDefault = "0";
    });
  } catch (error) {
    ElMessage.error("获取添加Sku初始化动态数据失败");
  }
};

// 挂载完成发请求获取添加sku的初始化动态数据
onMounted(() => {
  getAddSkuFormInitData();
});

// 收集+号 sku数据
const skuForm = reactive<SkuData>({
  // 从爹那直接拿，直接收集好了
  spuId: "",
  tmId: "",
  category3Id: "",
  // v-model自己收集，都收集好了
  price: "",
  skuName: "",
  skuDesc: "",
  weight: "",
  // 以下需要我们敲代码自己收集
  skuDefaultImg: "", //下面setDefaultImg回调函数收集到
  skuImageList: [], //下面整理 handleSelectionChange回调
  // 整理收集
  skuAttrValueList: [],
  skuSaleAttrValueList: [],
});
const skuImageList = ref<SkuImageData[]>([]);
//图片列表的回调  handleSelectionChange
const handleSelectionChange = (val: SkuImageData[]) => {
  // console.log(val); val是选择的sku图片列表 不能把spu的图片列表覆盖,要重新定义一个skuImageList去收集
  // Proxy(Object) {id: 19, spuId: 4, imgName: '19b3……', imgUrl: 'http……'}
  skuImageList.value = val; // 收集先放在外面,最后整理完成再放到skuForm里面（还未收集）
};
// ---------------------------
//设置默认图片的回调   setDefaultImg
const setDefaultImg = (row: SpuImageData, spuImageList: SpuImageData[]) => {
  // console.log(row, spuImageList);
  // row打印出： Proxy(Array)  {id: 3578, spuId: 1176, imgName: '三五.webp', imgUrl: 'blob:http……', isDefault: '0'}
  // spuImageList打印出以下：
  // 0: {id: 3578, spuId: 1176, imgName: '三五.webp', imgUrl: 'blob:http……', isDefault: '0'}
  // 1: {id: 3579, spuId: 1176, imgName: '三五2.webp', imgUrl: 'blob:http……', isDefault: '0'}
  spuImageList.forEach((item) => (item.isDefault = "0"));
  row.isDefault = "1";
  skuForm.skuDefaultImg = row.imgUrl; //这里真正收集到skuForm的默认图片地址
};
// 点击保存按钮触发事件
const save = async () => {
  // 获取参数
  let sku = skuForm;
  // 1、获取收集好的参数数据
  // 2、整理收集好的参数数据
  // 爹的数据先拿过来
  // spuId: "",
  // tmId: "",
  // category3Id: "",
  sku.spuId = props.spu.id as number;
  sku.tmId = props.spu.tmId as number;
  sku.category3Id = props.spu.category3Id;
  // 整理图片列表
  sku.skuImageList = skuImageList.value.map((item) => {
    return {
      id: item.id,
      skuId: sku.id,
      imgName: item.imgName,
      imgUrl: item.imgUrl,
      spuImgId: item.id,
      isDefault: item.isDefault,
    };
  });
  // 整理sku的平台属性值列表
  sku.skuAttrValueList = attrList.value.reduce((prev, item) => {
    if (item.attrIdValueId) {
      let [attrId, valueId] = item.attrIdValueId.split(":");
      let obj = { attrId, valueId };
      prev.push(obj);
    }
    return prev;
  }, [] as SkuAttrValueData[]);
  // 整理sku的销售属性值列表
  sku.skuSaleAttrValueList = spuSaleAttrList.value.reduce((prev, item) => {
    if (item.saleAttrIdValueId) {
      let [saleAttrId, saleAttrValueId] = item.saleAttrIdValueId.split(":");
      let obj = { saleAttrId, saleAttrValueId };
      prev.push(obj);
    }
    return prev;
  }, [] as SkuSaleAttrValueData[]);

  // 3、发送请求
  try {
    await skuApi.saveSkuInfo(sku);
    // 4、成功干啥
    ElMessage.success("添加sku成功");
    emits("changeState", 1);
  } catch (error) {
    // 5、失败干啥
    ElMessage.error("添加sku失败");
  }
};
</script>

<style lang="scss" scoped></style>